package com.chinatelecom.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.org.rapid_framework.generator.provider.db.table.TableFactory;
import cn.org.rapid_framework.generator.provider.db.table.model.Table;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

/**
 * word工具生成表信息（设计文档的编写）
 * 
 * <#list tableList as table>
 * 
 * ${table.remarks}(${table.sqlName})
 * 
 * <#list table.columns as column>
 * 
 * ${column.sqlName} ${column.sqlTypeName} ${column.remarks}
 * 
 * <#if column.nullable>YES<#else>NO</#if>
 * 
 * <#if column.pk>√</#if>
 * 
 * </#list>
 * 
 * </#list>
 * 
 */
@Slf4j
public class WordUtils {

	private static Configuration configuration = null;

	static {
		configuration = new Configuration(Configuration.VERSION_2_3_0);
		configuration.setDefaultEncoding("utf-8");
		try {
			configuration.setClassForTemplateLoading(WordUtils.class, "/com/chinatelecom/tool");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * java接口，生成word
	 * 
	 * @param templateFile 模板文件
	 * @param templateData 模板数据
	 * @param outputFile   生成的文件名
	 */
	public static void createWord(String templateFile, Map<String, Object> templateData, String outputFile) {
		try {
			Template t = configuration.getTemplate(templateFile);
			File f = new File(outputFile);
			Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
			t.process(templateData, w);
			w.close();
			log.info("生成word文档成功，文件：{}", f.getAbsoluteFile());
		} catch (Exception e) {
			log.error("生成word文档出错", e);
		}
	}

	/**
	 * 获取表信息
	 */
	private static Map<String, Object> getDataMap() {
		Map<String, Object> map = new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		List<Table> tableList = TableFactory.getInstance().getAllTables();
		map.put("tableList", tableList);
		return map;
	}

	public static void main(String[] args) {
		String templateFile = "table.xml";
		String outputFile = "C:/Users/darcy/Desktop/xx系统架构设计.doc";
		Map<String, Object> map = getDataMap();
		WordUtils.createWord(templateFile, map, outputFile);
	}
}
